package com.openbravo.pos.printer;

import cn.ekuma.epos.bean.util.sale.TicketLineWarp;
import cn.ekuma.epos.bean.util.sale.TicketWarp;

import com.openbravo.bean.sales.TicketLine;
import com.openbravo.pos.sales.TicketsEditor;
import com.openbravo.pos.sales.event.TicketEvent;
import com.openbravo.pos.sales.event.TicketLineEvent;
import com.openbravo.pos.scripting.ScriptEngine;
import com.openbravo.pos.scripting.ScriptException;
import com.openbravo.pos.scripting.ScriptFactory;

public class RealTicketPrintManager extends AbstractTicketPrintManager{

	ScriptEngine script;

	public RealTicketPrintManager(TicketParser ticketParser,
			TicketsEditor ticketEditor) throws ScriptException {
		super(ticketParser, ticketEditor);
		script = ScriptFactory.getScriptEngine(ScriptFactory.VELOCITY);
	}

	@Override
	public void fireTicketCreated(TicketEvent e) throws TicketPrinterException, ScriptException {
       ticketEditor.printTicket("Printer.Ticket.Real.Head", e.getSource(), ticketEditor.getTicketExt());
	   for(TicketLine l:e.getSource().getLines()){
		   printTicketLine(l);
	   }
	}

	@Override
	public void fireTicketFlushed(TicketEvent e) throws TicketPrinterException, ScriptException {
        ticketEditor.printTicket("Printer.Ticket.Real.Foot", e.getSource(), ticketEditor.getTicketExt());
	}

	@Override
	public void fireTicketDeleted(TicketEvent e) throws TicketPrinterException, ScriptException {
        ticketEditor.printTicket("Printer.Ticket.Real.DeleteTicket", e.getSource(), ticketEditor.getTicketExt());
	}

	
	@Override
	public void fireTicketSaved(TicketEvent e) throws TicketPrinterException {
        ticketEditor.printTicket("Printer.Ticket.Real.SaveTicket", e.getSource(), ticketEditor.getTicketExt());

	}

	@Override
	public void fireTicketLineAdded(TicketLineEvent e) throws TicketPrinterException, ScriptException {
		printTicketLine(e.getSource());

	}

	@Override
	public void fireTicketLineChanged(TicketLineEvent e) throws TicketPrinterException, ScriptException {
		TicketLine temp=e.getSource();
		temp.setMultiply(e.getDest().getMultiply()-temp.getMultiply());
		printTicketLine(temp);

	}

	@Override
	public void fireTicketLineDeleted(TicketLineEvent e) throws TicketPrinterException, ScriptException {
		TicketLine temp=e.getSource();
		temp.setMultiply(-temp.getMultiply());
		printTicketLine(temp);

	}
	
	private void printTicketLine(TicketLine l) throws TicketPrinterException, ScriptException{
		String sresource = ticketEditor.getDlSystem().getResourceAsXML("Printer.Ticket.Real.Body");
		script.put("ticketline",new TicketLineWarp(l));
        ticketParser.printTicket(script.eval(sresource).toString());
	}

}
